import { defineStore } from "pinia";
import { ref,watch } from "vue";


const STORAGE_KEY = 'user_login_info'

export const useUserStore = defineStore('user',() => {
    const isLoggedIn = ref(false);
    const username = ref('');
    const role = ref('');

    const loadUser = () => {
        const storedData = localStorage.getItem(STORAGE_KEY)
        if (storedData) {
            const userData = JSON.parse(storedData)
            isLoggedIn.value = userData.isloggedIn
            username.value = userData.username
            role.value = userData.role

        }
    }

    const login = (user) => {
        isLoggedIn.value = true
        username.value = user.username
        role.value = user.role

        
        localStorage.setItem(
            STORAGE_KEY,
            JSON.stringify({isloggedIn:true,username:user.username,role:user.role})
        )

    }

    const logout = () =>{
        isLoggedIn.value = false
        username.value = ''
        role.value = ''
        localStorage.removeItem(STORAGE_KEY)
    };

    watch (
        [isLoggedIn,username,role],
        () => {
            if (isLoggedIn.value) {
                localStorage.setItem(
                    STORAGE_KEY,
                    JSON.stringify({isLoggedIn:isLoggedIn.value,username: username.value,role:role.value})
                )
            }
        },
        { deep: true}
    )

    loadUser()
    return {isLoggedIn,username,role,login,logout};
})